package com.cennavi.minemapdemo.util;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.os.Environment;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**SD卡中的文件相关工具类
 * Created by jingru on 2016/6/29.
 */
public class SDFileConfig {
    private static final String MineNavi_DIR = "minenavi_ol";
    public static final String GUIDE_DIR = "guide";
    public static final String ADV_DIR = "adv";
    public static final String CAR_PARK = "carpark";
    public static String ANDROID_JSON = "minenavi_android";
    public static String APK_VERSION_CODE_NAME = "versioncode";
    public static String APP_FILES_PATH = "";
    public static String SDKCARD_PATH = "";
    public static final String VERSION_CODE = "verCode";

    public static final String MAP_DIR = "map";

    /**
     * SD卡上配置文件的目录
     */
    public static final String CONFIG = "config";
    /**
     * 用户设置信息
     */
    public static final String USER_SETTING = "user_setting";
    /**
     * js的头部
     */
    public static final String JSON_HEADER = "{'minenavi_android':{}}";
    /**
     * 斜杠
     */
    public static String SLASH = "/";

    /**
     * 读写检查
     * @return
     */
    public static boolean isExternalStorageWritable(){
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)){
            return true;
        }
        return false;
    }

    /**
     * 只读检查
     * @return
     */
    public static boolean isExternalStorageReadable(){
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
            return true;
        }
        return false;
    }

    public static String getAppPath() {
        String path = null;
        if (APP_FILES_PATH != null&&!APP_FILES_PATH.equals("")){
            path = APP_FILES_PATH + SLASH + MineNavi_DIR;
        }
        return path;
    }

    public static String getMineMapSDKPath() {
        String path = null;
        //TODO
        if (ValueUtil.isStringValid(SDKCARD_PATH)){
            path = SDKCARD_PATH + SLASH + "minemap";
        }else {
            SDKCARD_PATH = Environment
                    .getExternalStorageDirectory().toString();
            path = SDKCARD_PATH + SLASH + "minemap";
        }
        return path;
    }

    /**
     * android data 内的程序包名
     * @return
     */
    public static String getAndroidTypefacePath() {
        String path = null;
        //TODO
        if (ValueUtil.isStringValid(SDKCARD_PATH)){
            path = SDKCARD_PATH + SLASH + "Android/data/com.minenavi";
        }else {
            SDKCARD_PATH = Environment
                    .getExternalStorageDirectory().toString();
            path = SDKCARD_PATH + SLASH + "Android/data/com.minenavi";
        }
        return path;
    }

    public static String getAppSDKPath() {
        String path = null;
        //TODO
        if (ValueUtil.isStringValid(SDKCARD_PATH)){
            path = SDKCARD_PATH + SLASH + MineNavi_DIR;
        }else {
            SDKCARD_PATH = Environment
                    .getExternalStorageDirectory().toString();
            path = SDKCARD_PATH + SLASH + MineNavi_DIR;
        }
        return path;
    }
    public static String getUserImageDirectory() {
        String path = null;
        //TODO
        if (APP_FILES_PATH != null){
            path = APP_FILES_PATH + SLASH + MineNavi_DIR + SLASH +"user"+SLASH;
        }
        File dir = new File(APP_FILES_PATH + SLASH + MineNavi_DIR + SLASH +"user"+SLASH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return path;
    }
    public static String getTTsDirectory() {
        String path = getAppSDKPath()+SLASH +"tts"+SLASH;
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        return path;
    }

    /**
     * 分享截图地址
     * @return
     */
    public static String getShareIconPath() {
        String path = null;
        if (ValueUtil.isStringValid(SDKCARD_PATH)){
            path = SDKCARD_PATH + SLASH + MineNavi_DIR + SLASH +"image"+SLASH;
        }else {
            SDKCARD_PATH = Environment
                    .getExternalStorageDirectory().toString();
            path = SDKCARD_PATH + SLASH + MineNavi_DIR + SLASH +"image"+SLASH;
        }
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        return path;
    }

    public static String getSimpleTMCLoadImagePath(String bandId) {
        String imageUrl = SDFileConfig.getSimpleTMCLoadImageDirectory() + bandId;
//        + ".png";
        return imageUrl;
    }

    public static String getActivityPngImagePath(int id) {
        String imageUrl = SDFileConfig.getActivityPngImageDirectory() + id;
//        + ".png";
        return imageUrl;
    }

    /**
     * 简图灰图地址
     * @return
     */
    public static String getSimpleTMCLoadImageDirectory() {
        String path = null;
        if (APP_FILES_PATH != null){
            path = APP_FILES_PATH + SLASH + MineNavi_DIR + SLASH +"SimpleTMCLoad"+SLASH;
        }
        File dir = new File(APP_FILES_PATH + SLASH + MineNavi_DIR + SLASH +"SimpleTMCLoad"+SLASH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return path;
    }

    /**
     * 闪屏SDK地址
     * @return
     */
    public static String getActivityPngImageDirectory() {
        String path = null;
        if (ValueUtil.isStringValid(SDKCARD_PATH)){
            path = SDKCARD_PATH + SLASH + MineNavi_DIR + SLASH +"ActivityPng"+SLASH;
        }else {
            SDKCARD_PATH = Environment
                    .getExternalStorageDirectory().toString();
            path = SDKCARD_PATH + SLASH + MineNavi_DIR + SLASH +"ActivityPng"+SLASH;
        }
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return path;
    }

    public static String getUserImagePath() {
        String path = null;
        //TODO
        if (APP_FILES_PATH != null){
            path = APP_FILES_PATH + SLASH + MineNavi_DIR + SLASH +"user"+SLASH+"user_photo" + ".jpg";
        }
        File dir = new File(APP_FILES_PATH + SLASH + MineNavi_DIR + SLASH +"user"+SLASH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return path;
    }

    /**
     * 获得用户设置
     * @return
     */
    public static File getUserSettingFile(){

        File file = null;
        try {
            String path = getAppPath() +
                    SLASH + CONFIG ;
            File filedir = new File(path);
            if (!filedir.exists()) {
                filedir.mkdirs();
            }
            file = new File(filedir, USER_SETTING);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        return file;
    }



    public static boolean saveShareBitmap(String bitName, Bitmap myBmp) throws IOException
    {
        try{
            File myCaptureFile = new File(bitName);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            myBmp.compress(Bitmap.CompressFormat.JPEG, 20, bos);
            bos.flush();
            bos.close();
        }catch(Exception e){
            e.printStackTrace();
            java.lang.System.gc();
            if(myBmp!=null){
                myBmp.recycle();
                myBmp = null;
            }
        }
        return true ;
    }
    public static boolean saveShareBitmap(String bitName, Bitmap myBmp, int quality) throws IOException
    {
        try{
            File myCaptureFile = new File(bitName);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            myBmp.compress(Bitmap.CompressFormat.JPEG, quality, bos);
            bos.flush();
            bos.close();
        }catch(Exception e){
            e.printStackTrace();
            java.lang.System.gc();
            if(myBmp!=null){
                myBmp.recycle();
                myBmp = null;
            }
        }
        return true ;
    }

    /*public static boolean copyAssetsFilesToData(Context context,String inPath,String outPath) {
//        String inPath = "";
//        String outPath = "/sdcard/mydir";
        long begin = System.currentTimeMillis();
        boolean ret = copyFiles(context, inPath, outPath);
        long end = System.currentTimeMillis();
        return ret;
    }*/


    public static String getJsonFile(Context mContext, String fileName) {

        StringBuilder sb = new StringBuilder();
        AssetManager am = mContext.getAssets();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    am.open(fileName)));
            String next = "";
            while (null != (next = br.readLine())) {
                sb.append(next);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            sb.delete(0, sb.length());
        }
        return sb.toString().trim();
    }

    /**
     * 从assets目录下拷贝整个文件夹，不管是文件夹还是文件都能拷贝
     *
     * @param context
     *            上下文
     * @param inPath
     *            文件目录，要拷贝的目录
     * @param outPath
     *            目标文件夹位置如：/sdcrad/mydir
     */
    public static boolean copyFiles(Context context, String inPath, String outPath) {
        String[] fileNames = null;
        try {// 获得Assets一共有几多文件
            fileNames = context.getAssets().list(inPath);
        } catch (IOException e1) {
            e1.printStackTrace();
            return false;
        }
        if (fileNames.length > 0) {//如果是目录
            File fileOutDir = new File(outPath);
            if(fileOutDir.isFile()){
                boolean ret = fileOutDir.delete();
                if(!ret){
                }
            }
            if (!fileOutDir.exists()) { // 如果文件路径不存在
                if (!fileOutDir.mkdirs()) { // 创建文件夹
                    return false;
                }
            }
            for (String fileName : fileNames) { //递归调用复制文件夹
                String inDir = inPath;
                String outDir = outPath + File.separator;
                if(!inPath.equals("")) { //空目录特殊处理下
                    inDir = inDir + File.separator;
                }
                copyFiles(context,inDir + fileName, outDir + fileName);
            }
            return true;
        } else {//如果是文件
            try {
                File fileOut = new File(outPath);
                if(fileOut.exists()) {
                    boolean ret = fileOut.delete();
                    if(!ret){
                    }
                }
                boolean ret = fileOut.createNewFile();
                if(!ret){
                }
                FileOutputStream fos = new FileOutputStream(fileOut);
                InputStream is = context.getAssets().open(inPath);
                byte[] buffer = new byte[1024];
                int byteCount=0;
                while((byteCount = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, byteCount);
                }
                fos.flush();//刷新缓冲区
                is.close();
                fos.close();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    public static boolean haseMapDate(String path){
        try {
            int num = 0;
            File fileOut = new File(path);
            if(fileOut.exists()) {
                File f[] =  fileOut.listFiles();
                for (File one:f) {
                    String name= one.getName();
                    switch (name){
                        case "1chongqing.dat":
                        case "1chongqing.db":
                        case "base.dat":
                        case "base.db":
                        case "cmr.db":
                            num++;
                            break;
                    }
                }
            }
            if (num == 5){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }
}
